import android.content.Context
import android.database.SQLException
import androidx.room.Room
import androidx.room.migration.AutoMigrationSpec
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
/**
 * Room数据工具类
 */
object RoomDBUtils {

    private const val parkDataBaseName = "video.db"
    private lateinit var roomDb: AppDataBase

    //普通升级
    private val MIGRATION_2_3 = object : Migration(2,3){
        override fun migrate(database: SupportSQLiteDatabase) {
            try {//使用SQL语句来升级数据库
                val renameTableSQL = "ALTER TABLE user_info_table RENAME TO user_info"
                database.execSQL(renameTableSQL)
            } catch (e: SQLException) {
                e.printStackTrace()
            }
        }
    }

    //自动升级策略
    private val AUTO_MIGRATION_SPEC = object : AutoMigrationSpec{
        override fun onPostMigrate(db: SupportSQLiteDatabase) {
            super.onPostMigrate(db)
            try {//使用SQL语句来升级数据库
                val renameTableSQL = "ALTER TABLE user_info_table RENAME TO user_info"
                db.execSQL(renameTableSQL)
            } catch (e: SQLException) {
                e.printStackTrace()
            }
        }
    }


    /**
     * 初始化
     */
    fun initRoom(ctx: Context){
        roomDb = Room.databaseBuilder(ctx, AppDataBase::class.java, parkDataBaseName)
//            .addMigrations(MIGRATION_2_3)
//            .addAutoMigrationSpec(AUTO_MIGRATION_SPEC)
            .build()
    }

    /**
     * 获取操作DAO
     */

    fun getDataBase(): AppDataBase{
        if (roomDb == null){
            throw RuntimeException("数据库还没有初始化！！")
        }
        return roomDb
    }


}